import { local, session, cookie } from '@/libs/storage'
import { getMasterDomain, isDomainAddress } from '@/libs/tools/common'

export default {
  state: {
    token: cookie.get('token') /* 用户token */,
    user: cookie.get('user') /* 用户信息 */,
    shareData: session.get('shareData') /* 分享信息 */,
    openId: local.get('openId') /* 用户信息 */
  },
  getters: {
    getToken: state => state.token,
    getUser: state => state.user,
    getShareData: state => state.shareData,
    getOpenId: state => state.openId,
    isLogin: state => state.user && state.token
  },
  mutations: {
    setShareData(state, value) {
      state.shareData = value
    },
    setToken(state, value) {
      state.token = value
      const domain = isDomainAddress() ? { domain: getMasterDomain() } : undefined
      value ? cookie.set('token', value, domain) : cookie.remove('token', domain)
    },
    setUser(state, value) {
      /** 清除关注老师列表 */
      if (value && value.followTeachers) value.followTeachers = null
      state.user = value
      const domain = isDomainAddress() ? { domain: getMasterDomain() } : undefined
      value ? cookie.set('user', value, domain) : cookie.remove('user', domain)
    },
    setOpenId(state, value) {
      state.openId = value
      value ? local.set('openId', value) : local.remove('openId', value)
    }
  },
  actions: {
    login(state, { token, user }) {
      state.commit('setUser', user)
      state.commit('setToken', token)
    },
    logout(state) {
      state.commit('setUser')
      state.commit('setToken')
    }
  }
}
